import React, {useCallback, useEffect, useState} from "react"
import {ConfigProvider, Table} from "antd";
import DataPageLayout from "../../components/DataPageLayout";
import {NumberIdAndName} from "../../types/BasicModels";
import {useNavigate, useSearchParams} from "react-router-dom";
import {Pageable} from "../../utils/Page";
import {mergePaginationAndPageable, useTableFilterDateRangeColumnProps} from "../../utils/AntdTableUtils";
import {observerDashboardPageWrapper} from "./ObserverDashboardPageWrapper";
import {
    ProcurementReceiptStatus, procurementReceiptStatuses,
    procurementReceiptStatusMap,
    QueryProcurementReceiptResponse,
    queryProcurementReceipts
} from "../../apis/ProcurementReceiptApi";
import {getAllProcurementSupplier} from "../../apis/ProcurementSupplierApi";
import {useGlobalStyle} from "../../global.style";
import {YEAR_MONTH_DAY_FORMATER} from "../../utils/Date";

export interface pageProps {

}


const ProcurementReceiptPage: React.FC<pageProps> = (props) => {
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryProcurementReceiptResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    let [urlSearchParams] = useSearchParams();
    const [supplierIds, setSupplierIds] = useState<number[]>(urlSearchParams.getAll("supplierIds").map(it => parseInt(it)))

    const [procurementSuppliers, setProcurementSuppliers] = useState<Array<NumberIdAndName>>([])
    useEffect(() => {
        getAllProcurementSupplier().then(response => {
            setProcurementSuppliers(response.data)
        })
    }, []);
    let globalStyle = useGlobalStyle();


    const [openAddDrawer, setOpenAddDrawer] = useState(false)

    const [startCreatedDate, setStartCreatedDate] = useState<string>()
    const [endCreatedDate, setEndCreatedDate] = useState<string>()
    const [startValidatedDate, setStartValidatedDate] = useState<string>()
    const [endValidatedDate, setEndValidatedDate] = useState<string>()
    const [status, setStatus] = useState<ProcurementReceiptStatus>()
    const query = useCallback(() => {
        setLoading(true)
        queryProcurementReceipts({
            supplierIds: supplierIds,
            startCreatedDate: startCreatedDate ? (startCreatedDate).toString() : undefined,
            endCreatedDate: endCreatedDate ? (endCreatedDate).toString() : undefined,
            validatedStartDate: startValidatedDate,
            validatedEndDate: endValidatedDate,
            status
        }, pageable).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), supplierIds, startCreatedDate, endCreatedDate, startValidatedDate, endValidatedDate, status])
    useEffect(() => {
        query()
    }, [query]);

    let navigate = useNavigate();

    return <>
        <DataPageLayout>
            <ConfigProvider componentSize={"small"}>
                <Table<QueryProcurementReceiptResponse> className={globalStyle.rowClickableTable} onRow={item => {
                    return {
                        onClick: () => {
                            navigate(`/procurements/receipts/${item.id}`)
                        }
                    }
                }} size={"small"} loading={loading} dataSource={data} rowKey={"id"} pagination={{
                    current: pageable.page,
                    pageSize: pageable.size,
                    total: totalElements,
                }} onChange={(pagination, filters, sorter) => {
                    setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                    setSupplierIds(filters["supplier.name"] as number[])
                    setStatus((filters["status"] as ProcurementReceiptStatus[])[0])
                }}>
                    {/*TODO*/}
                    <Table.Column<QueryProcurementReceiptResponse> filteredValue={supplierIds}
                                                                   dataIndex={["supplier", "name"]}
                                                                   key={"supplierIds"}
                                                                   title={"供货商"}
                                                                   filters={procurementSuppliers.map(supplier => {
                                                                       return {
                                                                           text: supplier.name,
                                                                           value: supplier.id,
                                                                       }
                                                                   })}
                                                                   render={(_, record) => {
                                                                       return record.supplier.name
                                                                   }}/>
                    <Table.Column dataIndex={"procurementCreatedDateTime"} title={"采购时间"}
                                  render={(value) => (value).format(YEAR_MONTH_DAY_FORMATER)}/>
                    <Table.Column dataIndex={"createdDateTime"} title={"开单时间"}
                                  {...useTableFilterDateRangeColumnProps<QueryProcurementReceiptResponse>("createdDateTime", {
                                      handleSearch: value => {
                                          setStartCreatedDate(value ? value[0].format() : undefined)
                                          setEndCreatedDate(value ? value[1].format() : undefined)
                                      }
                                  })}
                                  render={(value) => (value).format(YEAR_MONTH_DAY_FORMATER)}/>
                    <Table.Column dataIndex={"validatedDateTime"} title={"验货时间"}
                                  {...useTableFilterDateRangeColumnProps<QueryProcurementReceiptResponse>("validatedDateTime", {
                                      handleSearch: value => {
                                          setStartValidatedDate(value ? value[0].format() : undefined)
                                          setEndValidatedDate(value ? value[1].format() : undefined)
                                      }
                                  })}
                                  render={(value) => value?.format(YEAR_MONTH_DAY_FORMATER)}/>
                    <Table.Column dataIndex={["goodsKindAmount"]} title={"单品数量"}/>
                    <Table.Column<QueryProcurementReceiptResponse> dataIndex={"status"}
                                                                   filteredValue={status ? [status] : []}
                                                                   title={"状态"}
                                                                   key={"status"}
                                                                   filterMultiple={false}
                                                                   filters={procurementReceiptStatuses.map(it => ({
                                                                       text: procurementReceiptStatusMap[it],
                                                                       value: it
                                                                   }))} render={(_, record) => {
                        return procurementReceiptStatusMap[!record.validatedDateTime?'WAIT_VALIDATED':"VALIDATED"]
                    }}/>

                </Table>
            </ConfigProvider>

        </DataPageLayout>
    </>
}
export default observerDashboardPageWrapper(ProcurementReceiptPage, "procurements/receipts", "采购入库单")
